package com.chz.SupermarketMS.controllers;

import com.chz.SupermarketMS.dao.HeadRepository;
import com.chz.SupermarketMS.dao.PurchaseRepository;
import com.chz.SupermarketMS.dto.PurchaseHeads;
import com.chz.SupermarketMS.entities.Commodity;
import com.chz.SupermarketMS.entities.Head;
import com.chz.SupermarketMS.entities.Purchase;
import com.chz.SupermarketMS.service.PurchaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("purchases")
public class PurchaseController {

    @Autowired
    PurchaseService purchaseService;

    @Autowired
    PurchaseRepository purchaseRepository;

    @Autowired
    HeadRepository headRepository;

    @GetMapping
    public String displayPurchases(Model model){

        List<Purchase> purchases = purchaseService.getAll();
        model.addAttribute("purchases",purchases);

        List<PurchaseHeads> purchaseHeads=purchaseRepository.purchaseHeads();
        model.addAttribute("purchaseHeads",purchaseHeads);
        return "purchases/list-purchases";
    }

    @GetMapping("/new")
    public String displayPurchaseForm(Model model){

        Purchase aPurchase = new Purchase();
        model.addAttribute("purchase",aPurchase);

//        List<Head> heads=headRepository.findAll();
//        model.addAttribute("allHeads",heads);

        return "purchases/new-purchase";
    }

    @PostMapping("/save")
    public String createPurchase(Model model, @Valid Purchase purchase, Errors errors){

        if (errors.hasErrors()) return "purchases/new-purchase";

        purchaseService.save(purchase);
//        Iterable<Head> chosenHeads = headRepository.findAllById(heads);
//        for (Head head : chosenHeads){
//            head.setPurchases(purchase);

//        headRepository.save(heads);
//        }
        return "redirect:/purchases";
    }
    @GetMapping("/update")
    public String displayPurchaseUpdateForm(@RequestParam("id") long theId, Model model) {
        Purchase thePurchase = purchaseService.findByPurchaseId(theId);
        model.addAttribute("purchase", thePurchase);
        return "purchases/new-purchase";
    }
    @GetMapping("/delete")
    public String deletePurchase(@RequestParam("id")long theId, Model model) {
        Purchase thePurchase = purchaseService.findByPurchaseId(theId);
        purchaseService.delete(thePurchase);
        return "redirect:/purchases";
    }
}
